import History from './base'
import { pushState } from '../utils/push-state'

export default class HTML5History extends History {
  constructor (router, { base }) {
    super(router, base)
    this.initEventLister()
  }

  initEventLister () {
    if (!location.pathname) {
      location.pathname = '/'
    }
    window.addEventListener('popstate', () => {
      this.current = location.pathname
    }, false)
  }

  push (location, onComplete, onAbort) {
    this.transitionTo(location, (route) => {
      pushState(route.path)
      onComplete && onComplete()
    })
  }

  getCurrentLocation () {
    const base = this.base
    let path = decodeURI(window.location.pathname)
    if (base && path.indexOf(base) === 0) {
      path = path.slice(base.length)
    }
    return (path || '/') + window.location.search + window.location.hash
  }
}
